Beginning Scala by Layka Vishal & Pollak David

Beginning Scala by Layka Vishal & Pollak David

Author:Layka, Vishal & Pollak, David
Language: eng
Format: epub
ISBN: 978-1-4842-0233-3
Publisher: Apress
Published: 2015-02-25T05:00:00+00:00


stream: scala.collection.immutable.Stream[Int] = Stream(1, ?)

you can attempt to access the head and tail of the stream. The head is returned immediately:

scala> stream.head

res0: Int = 1

but the tail isn't evaluated yet:

scala> stream.tail

res1: scala.collection.immutable.Stream[Int] = Stream(2, ?)

The ? symbol is the way a lazy collection shows that the end of the collection hasn’t been evaluated yet.

Tuples

Have you ever written a method that returns two or three values? Let’s write a method that takes a List[Double] and returns the count, the sum, and the sum of squares returned in a three-element Tuple, a Tuple3[Int, Double, Double]:

def sumSq(in: List[Double]): (Int, Double, Double) =

in.foldLeft((0, 0d, 0d))((t, v) => (t._1 + 1, t._2 + v, t._3 + v * v))

The sumSq method takes a List[Double] as input and returns a Tuple3[Int, Double, Double]. The compiler desugars (Int, Double, Double) into Tuple3[Int, Double, Double]. The compiler will treat a collection of elements in parentheses as a Tuple. We seed the foldLeft with (0, 0d, 0d), which the compiler translates to a Tuple3[Int, Double, Double]. The function takes two parameters: t and v. t is a Tuple3, and v is a Double. The function returns a new Tuple3 by adding 1 to the first element of the Tuple, adding v to the second element of the Tuple, and adding the square of v to the third element of the Tuple. Using Scala’s pattern matching, we can make the code a little more readable:

def sumSq(in: List[Double]) : (Int, Double, Double) =

in.foldLeft((0, 0d, 0d)){

case ((cnt, sum, sq), v) => (cnt + 1, sum + v, sq + v * v)}

You can create Tuples using a variety of syntax:

scala> Tuple2(1,2) == Pair(1,2)

scala> Pair(1,2) == (1,2)

scala> (1,2) == 1 -> 2

The last example, 1 -> 2, is a particularly helpful and syntactically pleasing way for passing pairs around. Pairs appear in code very frequently, including name/value pairs for creating Maps.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.